﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMS.Core.Types;
using CMS.Core;
using CMS.Web.Filters;
using CMS.Web.Areas.Admin.Models;
using CMS.Core.General;

namespace CMS.Web.Areas.Admin.Controllers
{
    [AdminAuthorize]
    public class UserController : Controller
    {
        // GET: Admin/User
        UserManager userManager = new UserManager();
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="userName"></param>
        /// <param name="name"></param>
        /// <param name="sex"></param>
        /// <param name="email"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="order"></param>
        /// <returns>Json</returns>
        public JsonResult FindPageJson(int? roleID, string userName, string name, int? sex, string email, int? pageIndex, int? pageSize, int? order)
        {
            Paging<User> pagingUser = new Paging<Core.User>();

            if (pageIndex != null && pageIndex > 0)
                pagingUser.PageIndex =(int) pageIndex;
            if (pageSize != null && pageSize > 0)
                pagingUser.PageSize =(int) pageSize;

            Paging<User> paging = userManager.FindListPage(pagingUser, roleID, userName, name, sex, email, null);
           
            return Json(new {  total = paging.TotalItems, rows = paging.Items }, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns>1--成功, 其他-失败</returns>
        public JsonResult DeleteJson(int id)
        {
            var resp = userManager.Delete(id);

            if(resp.Code != 1)
            {
                resp.Message = "删除用户失败";
            }

            return Json(resp, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 验证用户名是否存在
        /// </summary>
        /// <param name="Username"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CanUserName(string Username)
        {
            return Json(!userManager.HasUserName(Username));
        }

        /// <summary>
        /// 验证Email是否存在
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CanEmail(string Email)
        {
            return Json(!userManager.HasEmail(Email));
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            var roleList = new RoleManager().FindList();
            List<SelectListItem> listItems = new List<SelectListItem>(roleList.Count());

            foreach(var role in roleList)
            {
                listItems.Add(new SelectListItem { Text = role.Name, Value = role.RoleID.ToString() });
            }

            ViewBag.Roles = listItems;

            return View();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns>成功-重定向成功页面,失败-提示</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(AddUserViewModel userInfo)
        {
            if (userManager.HasUserName(userInfo.Username))
                ModelState.AddModelError("Username", "该用户名已经被注册");
            if (userManager.HasEmail(userInfo.Email))
                ModelState.AddModelError("Email", "该Email已经被注册");

            Response response = new Core.Types.Response();

            if(ModelState.IsValid)
            {
                CMS.Core.User user = new Core.User()
                {
                    RoleID = userInfo.RoleID,
                    Username = userInfo.Username,
                    Name = userInfo.Name,
                    Sex = userInfo.Sex,
                    Password = Core.General.Security.Sha256(userInfo.Password),
                    Email = userInfo.Email,
                    RegTime = DateTime.Now
                };

                response = userManager.Add(user);

                if(response.Code == 1)
                {
                    Prompt prompt = new Models.Prompt()
                    {
                        Title = "添加成功",
                        Message = "用户 " + userInfo.Username + " 添加成功",
                        Buttons = new List<string>()
                        {
                           "<a href=\"" + Url.Action("Index", "User") + "\" class=\"btn btn-default\">用户管理</a>",
                            "<a href=\"" + Url.Action("Details", "User",new { id= response.Data.UserID }) + "\" class=\"btn btn-info\">查看用户</a>",
                            "<a href=\"" + Url.Action("Add", "User") + "\" class=\"btn btn-success\">继续添加</a>"
                        }
                    };

                    return View("_Prompt", prompt);
                }
                else
                {
                    ModelState.AddModelError("", response.Message);
                }
                
            }

            //角色列表
            var roleList = new RoleManager().FindList();
            List<SelectListItem> listItems = new List<SelectListItem>(roleList.Count());
            
            foreach(var role in roleList)
            {
                listItems.Add( new SelectListItem() { Text = role.Name, Value = role.RoleID.ToString() });
            }

            ViewBag.Roles = listItems;

            return View(userInfo);
        }

        /// <summary>
        /// 通过ID找到角色的名字
        /// </summary>
        /// <param name="id"></param>
        /// <returns>角色的名字</returns>
        public ActionResult FindRole(int id)
        {
            var role = new RoleManager().Find(id);
            
            return Json(role, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户信息和角色信息</returns>
        public ActionResult Modify(int id)
        {
            var roles = new RoleManager().FindList();
            List<SelectListItem> list = new List<SelectListItem>(roles.Count());

            foreach(var role in roles)
            {
                list.Add(new SelectListItem() { Text = role.Name, Value = role.RoleID.ToString() });
            }

            ViewBag.Roles = list;

            return PartialView(userManager.Find(id));
        }

        /// <summary>
        /// Post 修改用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="form">Post的用户信息</param>
        /// <returns>0-失败,1-成功</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Modify(FormCollection form)
        {
            Response response = new Core.Types.Response();
            var user = userManager.Find(Convert.ToInt32(form["UserID"]));
            var name = form["Name"];
            var ID = form["UserID"];
            //填入需要更新的Key,value from controller provider
            if (TryUpdateModel(user, new string[] { "RoleID", "Name", "Password", "Email","Sex" } ))
            {
                if(user == null)
                {
                    response.Code = 0;
                    response.Message = "用户不存在,可能已经被删除";
                }
                else
                {
                    if (user.Password != form["Password"])
                        user.Password = Security.Sha256(form["Password"]);
                    //update
                    response = userManager.Update(user);
                }
            }
            else
            {
                response.Code = 0;
                response.Message = Web.General.GetModelErrorString(ModelState);
            }

            return Json(response, JsonRequestBehavior.AllowGet);
        }

    }
}